package com.dayatang.product.webapp.action.mail;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.struts2.convention.annotation.Result;

import com.dayatang.product.domain.Customer;
import com.dayatang.product.domain.HtmlMail;
import com.dayatang.product.domain.SendMail;
import com.dayatang.product.webapp.executor.MailTaskExecutor;

@Result(name = "save", type = "redirect", location = "/mail/send-mail-manage.action")
public class SendMailPreviewAction extends MailBaseAction {

	private static final long serialVersionUID = -3817623273884340726L;

	private long mailId;
	private long[] recipients;
	private String operate;
	
	private HtmlMail htmlMail;
	private List<Customer> customers;
	
	@Inject
	private MailTaskExecutor mailTaskExecutor;
	
	public String execute() throws Exception {
		
		if (mailId > 0 && recipients.length > 0 && operate != null) {
			
			htmlMail = HtmlMail.get(HtmlMail.class, mailId);
			customers = new ArrayList<Customer>();
			for (long regId : recipients) {
				Customer customer = Customer.get(Customer.class, regId);
				if (customer != null) {
					customers.add(customer);
				}
			}
			
			productApplication.saveSendMailInfo(htmlMail, customers);
			
			if (operate.equals("preview")) {
				return SUCCESS;
			} else if (operate.equals("save")) {
				mailTaskExecutor.sendMail(SendMail.getSendMailByAbstractMail(htmlMail));
				return "save";
			}
			
		}
		
		return "save";
	}

	public long getMailId() {
		return mailId;
	}

	public void setMailId(long mailId) {
		this.mailId = mailId;
	}

	public long[] getRecipients() {
		return recipients;
	}

	public void setRecipients(long[] recipients) {
		this.recipients = recipients;
	}

	public String getOperate() {
		return operate;
	}

	public void setOperate(String operate) {
		this.operate = operate;
	}
	
	public void setMailTaskExecutor(MailTaskExecutor mailTaskExecutor) {
		this.mailTaskExecutor = mailTaskExecutor;
	}

	public HtmlMail getHtmlMail() {
		return htmlMail;
	}

	public List<Customer> getCustomers() {
		return customers;
	}
	
}
